const api = require('../../network/api')
const http = require('../../network/http')
var util = require('../../utils/dateTime.js');

import * as echarts from '../../libs/ec-canvas/echarts';
// 饼图 option
// let option = {
//   // 初始化数据
//   color: ['#5AD8A6', '#5B8FF9'], 
//   series: [{
//     name: '访问来源',
//     type: 'pie',
//     radius: ['50%', '70%'],
//     avoidLabelOverlap: false,
//     label: {
//       show: false,
//       position: 'center',
//     },
//     emphasis: {
//       label: {
//         show: true,
//         fontSize: '20',
//         fontWeight: 'bold',
//       },
//     },
//     labelLine: {
//       show: false,
//     },
//     data: [{
//         value: 335,
//         name: '微信支付'
//       },
//       {
//         value: 310,
//         name: '余额支付'
//       },
//     ],
//     itemStyle: {
//       emphasis: {
//         shadowBlur: 10,
//         shadowOffsetX: 0,
//         shadowColor: 'rgba(0, 0, 0, 0.5)',
//       },
//     },
//   }, ],
// };

let option = {
  xAxis: {
    data: ['微信', '余额', '抖音','美团','消费券'],
    axisLabel: {
      interval: 0,    //强制文字产生间隔
      // rotate: 45,     //文字逆时针旋转45°
      textStyle: {    //文字样式
        color: "black",
        fontSize: 12,
        fontFamily: 'Microsoft YaHei'
      },
    }  
  },
  yAxis: {
    axisLabel: {
      interval: 0,    //强制文字产生间隔
      // rotate: 45,     //文字逆时针旋转45°
      textStyle: {    //文字样式
        color: "black",
        fontSize: 8,
        fontFamily: 'Microsoft YaHei'
      },
    }  
  },
  series: [
    {
      type: 'bar',
      label: {
        show: false,
        position: 'top',
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '12',
          fontWeight: 'bold',
          color: '#000000',
        },
      },
      data: [{
        value: 43,
        itemStyle: {
          color: '#5AD8A6',
          shadowColor: '#5AD8A6',
          borderType: 'dashed',
          opacity: 0.9
        }
      }, {
        value: 29,
        itemStyle: {
          color: '#fcda43',
          shadowColor: '#fcda43',
          borderType: 'dashed',
          opacity: 0.9
        }
      }, {
        value: 29,
        itemStyle: {
          color: '#fc6f6f',
          shadowColor: '#fc6f6f',
          borderType: 'dashed',
          opacity: 0.9
        }
      }, {
        value: 29,
        itemStyle: {
          color: '#6bf3f8',
          shadowColor: '#6bf3f8',
          borderType: 'dashed',
          opacity: 0.9
        }
      }, {
        value: 29,
        itemStyle: {
          color: '#f06ffc',
          shadowColor: '#f06ffc',
          borderType: 'dashed',
          opacity: 0.9
        }
      }]
    }
  ]
};

let chart;
// 图表初始化
function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, // 像素
  });
  canvas.setChart(chart);
  chart.setOption(option);
  return chart;
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      onInit: initChart,
    },
    appdata: {
      appname: "测试商家",
      memberId: "",
    },
    currentRoom :"null",
    storeData: {
      area: '',
      areaCode: '',
      createBy: "",
      createTime: "",
      deleteFlag: false,
      dist: "",
      id: "",
      memberId: "",
      memberName: "null",
      regionLatitude: "",
      regionLongitude: "",
      state: 1,
      storeAddressDetail: "",
      storeDesc: "",
      storeImages: "",
      storeLogo: "",
      storeName: "",
      updateBy: null,
      updateTime: null,
      todaySalesPrice: '',
      salesPrice: 0,
      todayTrade: '',
      yesterdayTrade: '',
      sevenDaysTrade: '',
    },
    roomList: [],
    cleanRoomList: [],
    storeList: [],
    storeDetail: {},
    roomcancheckList: {},
    managerList: {},
    orderList: [],
    dataType: '0', //日报0，月报1
    chooseDate: '2022-10-27', //日报0，月报1
    chooseMonth: '2022-10',
    toDate: '', //日期选择的最大范围
    toMonth: '', //月份选择的最大范围
    showStore: false, //店铺弹窗
    showRoom: false, //房间操作弹窗
    roomType: 0, //房间操作弹窗页卡 
    windowRoomName: '', //选中的房间名
    choseRoomData: [],
    choseRoomSelect: [],
    windowRoomType: '', //选中的房间类别
    changeId: -1, //选中的换包ID
    timeIndex: 1, //开启房间时间选择
    openDurOur: '', //开启房间小时数
    openStartTime: '', //开启房间时间
    openFinishTime: '', //关闭房间结束时间
    openStartTImeFull: '', //开启房间时间完整
    openFinishTImeFull: '', //关闭房间时间完整
    chooseStatus: '0', //切换状态选中 0维护中，1，空闲中，2，使用中，3，清洁中
    identity: -1, // 登录者身份 0保洁 1店主 
    isLogin: false, //是否显示获取手机号按钮 false显示按钮 true显示数据页
    showToClean: false, //是否显示切换按钮
    doorStatus: '1', //开关门参数 1开门 0关门
    showNoClean: false, //显示无可打扫房间
    currentTime: '', //经营开启选择初始时间
    showCleanDo: false, //可清扫房间操作弹窗显示
    doCleanStatus: '1', //可清扫房间操作操作选项 1开门,0打扫完成
    chooseCleanData:{}, //选中的可清扫房间
    cleanTips: '',
    timeList: [],
    showPhone: false,
    numberValue: '',
    numberFocus: false,
  },

  showStore(e) {
    this.setData({
      showStore: !this.data.showStore,
    })
  },

  /**
   * 隐藏店铺列表弹窗
   */
  hiddenStore(e) {
    this.setData({
      showStore: false,
    })
  },
  /**
   * 隐藏房间操作弹窗
   */
  hiddenRoom(e) {
    if(this.data.numberFocus){
      wx.hideKeyboard();
    }else{
      this.setData({
        showRoom: false,
        showPhone: false,
      })
    }
  },
  /**
   * 隐藏清扫操作弹窗
   */
  hiddenCleanDo(e) {
    this.setData({
      showCleanDo: false,
    })
  },
  numFocusBlur(e){
    this.setData({
      numberFocus: false,
    })
  },
  numFocusBind(e){
    this.setData({
      numberFocus: true,
    })
  },
  /**
   * 选中店铺
   */
  chooseStore: function (e) {
    var $data = e.currentTarget.dataset;
    console.log($data.bean.storeName);
    this.setData({
      showStore: false,
      'storeData': $data.bean,
    })
    wx.setStorageSync('storeId', $data.bean.id);
    let identity = this.data.identity;
    if (identity == 1) {
      this.loadStroeDetail();
      this.loadBusinessData();
      // this.loadincome();
    } else {
      this.setData({
        'cleanRoomList': [],
      })
      this.loadCleanRoom();
    }

  },

  getPhoneNumber(e) {
    let that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      http.request({
        showLoading: true,
        url: api.login,
        method: "POST",
        data: {
          clientEnum: 1,
          code: e.detail.code,
        }
      }).then(res => {
        if (res.data.code == 200 && res.data.result != null) {
          wx.setStorageSync('phoneNum', res.data.result.mobile);
          wx.setStorageSync('identity', res.data.result.isSuper);
          wx.setStorageSync('memberId', res.data.result.memberId);
          var date = util.formatTime(new Date()).substring(0, 10);
          if (res.data.result.isSuper == 1) {
            this.setData({
              isLogin: true,
              toDate: date,
              chooseDate: date,
              toMonth: date.substring(0, 7),
              chooseMonth: date.substring(0, 7),
              identity: res.data.result.isSuper,
              showToClean: true,
              'appdata.memberId': res.data.result.memberId,
            });
            console.log(this.data.appdata.memberId + "++++++++++++++++");
            //获取用户ID
            that.loadStroeList();
          } else {
            this.setData({
              isLogin: true,
              identity: res.data.result.isSuper,
              'appdata.memberId': res.data.result.memberId,
            });
            that.loadStroeClean();
          }
        } else {
          wx.showToast({
            title: '该手机号为非商户管理员,请使用管理员手机号的微信进行登录',
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      });
    } else {
      wx.showToast({
        title: '拒绝获取手机号无法登入系统',
        icon: "none",
        duration: 2000
      })
    }
  },

  clickroomdetail: function (e) {
    var $data = e.currentTarget.dataset;
    console.log($data.bean);
    var detailId = $data.bean.tradeId;
    wx.navigateTo({
      url: '/pages/detail/detail?detailId=' + detailId,
    })
  },
  goOrder: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/orderFlow/orderFlow?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&dateType=1', 
    })
  },
  todayOrder: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/todayOrder/todayOrder?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&type=0',
    })
  },
  yesterdayOrder: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/todayOrder/todayOrder?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&type=1',
    })
  },
  goRechargeFlow: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/rechargeFlow/rechargeFlow?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&dateType=1'
      + '&merchantId=' + this.data.appdata.memberId,
    })
  },
  goOrderWX: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/orderFlow/orderFlow?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&dateType=1' + '&selectType=1', 
    })
  },
  goOrderMT: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/orderFlow/orderFlow?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&dateType=1' + '&selectType=2', 
    })
  },
  goOrderDY: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/orderFlow/orderFlow?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&dateType=1' + '&selectType=4', 
    })
  },
  goOrderCoupon: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/orderFlow/orderFlow?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id + '&dateType=1' + '&selectType=5', 
    })
  },
  goCensus: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/census/census?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id,
    })
  },
  goTest: function (e) {
    console.log(this.data.storeData);
    wx.navigateTo({
      url: '/pages/hardWare/hardWare?storeName=' + this.data.storeData.storeName + '&storeId=' + this.data.storeData.id,
    })
  },

  /**
   * 首页店铺查询
   */
  loadStroeList() {
    http.request({
      showLoading: true,
      url: api.storeList,
      data: {
        merchantId: this.data.appdata.memberId
        // merchantId: "1447138066175406034"
      },
    }).then(res => {
      if (res.data.code == 200 && (res.data.result).length > 0) {
        console.log("首页店铺列表返回:");
        console.log(res.data);
        if(wx.getStorageSync('storeId') != "" && wx.getStorageSync('storeId') != null){
          for(var i=0; i<res.data.result.length; i++){
            if(wx.getStorageSync('storeId') == res.data.result[i].id){
              this.setData({
                storeList: res.data.result,
                'storeData': res.data.result[i],
              })
              wx.setStorageSync('storeId', res.data.result[i].id);
            }
          }
        }else{
          this.setData({
            storeList: res.data.result,
            'storeData': res.data.result[0],
          })
          wx.setStorageSync('storeId', res.data.result[0].id);
        }
        if(wx.getStorageSync('identity') == 1){
          this.loadStroeDetail();
          this.loadBusinessData();
          // this.loadincome();
        }else{
          this.loadCleanRoom();
        }
        
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },
  loadStroeClean() {
    if(wx.getStorageSync('phoneNum') != '' && wx.getStorageSync('phoneNum') != null){
      wx.showToast({
        title: "手机号数据缺失",
        icon: "none",
        duration: 2000
      });
    }
    http.request({
      showLoading: true,
      url: api.storeClean,
      data: {
        mobile: wx.getStorageSync('phoneNum')
        // merchantId: "1447138066175406034"
      },
    }).then(res => {
      if (res.data.code == 200 && (res.data.result).length > 0) {
        console.log("清洁店铺列表返回:");
        console.log(res.data);
        this.setData({
          storeList: res.data.result,
          'storeData': res.data.result[0],
        })
        this.loadCleanRoom();
      }else if(res.data.code == 200 && (res.data.result).length == 0){
        wx.showToast({
          title: "未获取到店铺信息",
          icon: "none",
          duration: 2000
        });
      }else{
        wx.showToast({
          title: "店铺返回Code--" + res.data.code,
          icon: "none",
          duration: 2000
        });
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  /**
   * 获取经营数据
   */
  loadBusinessData() {
    let that = this
    http.request({
      showLoading: true,
      url: api.loadBusinessData,
      data: {
        storeId: this.data.storeData.id,
        // statisticsMode: this.data.dataType,
        // date: this.data.dataType == 0 ? this.data.chooseDate : this.data.chooseMonth,
        // statisticsMode: 1,
        // date: this.data.chooseMonth,
      },
    }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          'managerList': res.data.result,
        })
       
        //柱图
        var payList = [{
          value: res.data.result.realWePaySales,
          itemStyle: {
            color: '#5AD8A6',
            shadowColor: '#5AD8A6',
            borderType: 'dashed',
            opacity: 0.9
          }
        }, {
          value: res.data.result.balanceSales,
          itemStyle: {
            color: '#fcda43',
            shadowColor: '#fcda43',
            borderType: 'dashed',
            opacity: 0.9
          }
        }, {
          value: res.data.result.douYinSales,
          itemStyle: {
            color: '#fc6f6f',
            shadowColor: '#fc6f6f',
            borderType: 'dashed',
            opacity: 0.9
          }
        }, {
          value: res.data.result.meiTuanSales,
          itemStyle: {
            color: '#6bf3f8',
            shadowColor: '#6bf3f8',
            borderType: 'dashed',
            opacity: 0.9
          }
        }, {
          value: res.data.result.platformCouponSales,
          itemStyle: {
            color: '#f06ffc',
            shadowColor: '#f06ffc',
            borderType: 'dashed',
            opacity: 0.9
          }
        }]
        option.series[0].data = payList;
        if (chart) {
          chart.setOption(option);
        }
      }
    }).catch(err => {                                                                                                                                                                    
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  /**
   * 开启房间
   */
  openRoom(e) {
    let choseRoomData = this.data.choseRoomData;
    if (choseRoomData.state == '2') {
      wx.showToast({
        title: "该包间正在使用中，无法再次开启",
        icon: "none",
        duration: 2000
      });
    } else {
      http.request({
        showLoading: true,
        shake: true,
        url: api.startTrade,
        method: "POST",
        data: {
          durationTime: this.data.openDurOur,
          endDate: this.data.openFinishTImeFull,
          itemId: choseRoomData.id,
          memberId: this.data.appdata.memberId,
          memberName: this.data.appdata.appname,
          reserveDate: util.getcurNoHmm(new Date()),
          startDate: this.data.openStartTImeFull,
          totalPrice: (this.data.openDurOur * choseRoomData.price),
          mode: 0,
          mobile: "",
        },
      }).then(res => {
        if (res.data.code == 200) {
          if (res.data.result.startState == true) {
            this.hiddenRoom();
            if(res.data.result.code == 0){
              setTimeout(function () {
                wx.showToast({
                  title: '订单开启成功',
                  icon: "none",
                  duration: 2000
                });
              }, 1000);
            }else if(res.data.result.code == 1){
              setTimeout(function () {
                wx.showToast({
                  title: '订单预订成功',
                  icon: "none",
                  duration: 2000
                });
              }, 1000);
            }
            this.loadStroeDetail();
            this.loadBusinessData();
            // this.loadincome();
          } else {
            if (res.data.result.msg == null || res.data.result.msg == "") {
              wx.showToast({
                title: '下单失败,请稍后再试',
                icon: "none",
                duration: 2000
              });
            }else{
              wx.showToast({
                title: res.data.result.msg,
                icon: "none",
                duration: 2000
              });
            }
          }
        }
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      });
    }
  },
  showPhone(e){
    this.setData({
      showRoom: false,
      showPhone: true,
      numberValue: '',
      numberFocus: true,
    })
  },
  numInput: function (e) {
    this.setData({
      numberValue: e.detail.value
    })
    if(e.detail.value.length == 11){
      wx.hideKeyboard();
    }
    console.log(this.data.numberValue + "--------------")
  },
  custormerDo(e){
    if(this.data.numberValue == ''){
      wx.showToast({
        title: '请先输入用户手机号',
        icon: "none",
        duration: 2000
      });
    }else{
      let choseRoomData = this.data.choseRoomData;
      http.request({
        showLoading: true,
        shake: true,
        url: api.startTrade,
        method: "POST",
        data: {
          durationTime: this.data.openDurOur,
          endDate: this.data.openFinishTImeFull,
          itemId: choseRoomData.id,
          memberId: this.data.appdata.memberId,
          memberName: this.data.appdata.appname,
          reserveDate: util.getcurNoHmm(new Date()),
          startDate: this.data.openStartTImeFull,
          totalPrice: (this.data.openDurOur * choseRoomData.price),
          mode: 1,
          mobile: this.data.numberValue,
        },
      }).then(res => {
        if (res.data.code == 200) {
          if (res.data.result.startState == true) {
            this.hiddenRoom();
            if(res.data.result.code == 0){
              setTimeout(function () {
                wx.showToast({
                  title: '订单开启成功',
                  icon: "none",
                  duration: 2000
                });
              }, 1000);
            }else if(res.data.result.code == 1){
              setTimeout(function () {
                wx.showToast({
                  title: '订单预订成功',
                  icon: "none",
                  duration: 2000
                });
              }, 1000);
            }
            this.loadStroeDetail();
            this.loadBusinessData();
            // this.loadincome();
          } else {
            if (res.data.result.msg == null || res.data.result.msg == "") {
              wx.showToast({
                title: '下单失败,请稍后再试',
                icon: "none",
                duration: 2000
              });
            }else{
              wx.showToast({
                title: res.data.result.msg,
                icon: "none",
                duration: 2000
              });
            }
          }
        }
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      });
    } 
  },
  /**
   * 订单列表
   */
  loadincome() {
    http.request({
      showLoading: true,
      url: api.loadInCome,
      method: "GET",
      data: {
        storeId: this.data.storeData.id,
        date: this.data.chooseMonth,
      },
    }).then(res => {
      if (res.data.code == 200) {
        console.log("订单列表数据返回:");
        console.log(res.data.result);
        this.setData({
          'orderList': res.data.result,
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  chooseClearnRoom: function (e) {
    var $data = e.currentTarget.dataset;
    this.setData({
      chooseCleanData: $data.bean,
      showCleanDo: true,
      doCleanStatus: '1',
    })
  },
  openCleanDoor(e) {
    this.setData({
      doCleanStatus: '1',
    })
  },
  cleanFinish(e) {
    this.setData({
      doCleanStatus: '0',
    })
  },
  confirmClean(e){
    console.log(this.data.doCleanStatus + "---" + this.data.chooseCleanData.id)
    if(this.data.doCleanStatus == 1){
      http.request({
        showLoading: true,
        shake: true,
        url: api.openRoom,
        method: "GET",
        data: {
          itemId: this.data.chooseCleanData.id,
          operationType: 1,
        },
      }).then(res => {
        if (res.data.code == 200 && res.data.result) {
          wx.showToast({
            title: '开锁成功,请手动打开房门',
            icon: "none",
            duration: 2000
          });
          this.hiddenCleanDo();
        } else {
          wx.showToast({
            title: '操作失败，请检查锁的信号接收器是否正常',
            icon: "none",
            duration: 2000
          });
        }
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      });
    }else{
      http.request({
        showLoading: true,
        url: api.modifyItemInfo,
        method: 'POST',
        data: {
          aocn: this.data.chooseCleanData.aocn,
          aocnPathAddress: this.data.chooseCleanData.aocnPathAddress,
          describes: this.data.chooseCleanData.describes,
          enabled: this.data.chooseCleanData.enabled,
          itemLogo: this.data.chooseCleanData.itemLogo,
          itemName: this.data.chooseCleanData.itemName,
          pictures: this.data.chooseCleanData.pictures,
          price: this.data.chooseCleanData.price,
          id: this.data.chooseCleanData.id,
          smartAudio: this.data.chooseCleanData.smartAudio,
          smartLock: this.data.chooseCleanData.smartLock,
          state: '1',
          storeId: this.data.chooseCleanData.storeId,
          unit: this.data.chooseCleanData.unit,
          operateType : '0',
        },
      }).then(res => {
        if (res.data.code == 200) {
          this.hiddenCleanDo();
          setTimeout(function () {
            wx.showToast({
              title: "操作成功",
              icon: "none",
              duration: 2000
            });
          }, 1000);
          this.loadCleanRoom();
        } else {
          if (res.data.message == null || res.data.message == "") {
            wx.showToast({
              title: '修改状态失败,请稍后再试',
              icon: "none",
              duration: 2000
            });
          } else {
            wx.showToast({
              title: res.data.message,
              icon: "none",
              duration: 2000
            });
          }
        }
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      });
    }
  },
  changeIdentity: function (e) {
    if (wx.getStorageSync('identity') == 1) {
      if (this.data.identity == 1) {
        this.setData({
          identity: 0,
          'cleanRoomList': [],
        })
        this.loadCleanRoom();
      } else {
        this.setData({
          identity: 1,
        })
        this.loadStroeDetail();
        this.loadBusinessData();
        // this.loadincome();
      }
    }
  },

  loadCleanRoom() {
    http.request({
      showLoading: true,
      url: api.getNotCleanedItem,
      data: {
        storeId: this.data.storeData.id
      },
    }).then(res => {
      if (res.data.result == null) {
        this.setData({
          'cleanRoomList': [],
          showNoClean: true,
          // cleanTips: "当前店铺无可清扫房间",
        })
      } else if(res.data.code == 200 && res.data.result != null){
        this.setData({
          'cleanRoomList': res.data.result,
          showNoClean: false,
        })
      }else {
        wx.showToast({
          title: "房间返回Code--" + res.data.code,
          icon: "none",
          duration: 2000
        });
      }
      console.log(this.data.showNoClean + '-*-------');
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  /**
   * 获取门店详情
   */
  loadStroeDetail() {
    http.request({
      showLoading: true,
      url: api.loadStoreDetail,
      data: {
        storeId: this.data.storeData.id
      },
    }).then(res => {
      if (res.data.code == 200) {
        var newTimeList = [];
        for(var i=0; i<res.data.result.items.length; i++){
          var time = {
            lastEndTime: '',
            nextStartTime: '',
          }
          if(res.data.result.items[i].lastEndTime == null){
            time.lastEndTime = '无';
          }else{
            time.lastEndTime = res.data.result.items[i].lastEndTime.substring(5,16);
          }
          if(res.data.result.items[i].nextStartTime == null){
            time.nextStartTime = '无';
          }else{
            time.nextStartTime = res.data.result.items[i].nextStartTime.substring(5,16);
          }
          newTimeList.push(time);
        } 
        this.setData({
          'storeDetail': res.data.result,
          'roomList': res.data.result.items,
          timeList: newTimeList,
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    if (wx.getStorageSync('phoneNum') != '' && wx.getStorageSync('phoneNum') != null) {
      that.setData({
        identity: wx.getStorageSync('identity'),
        'appdata.memberId': wx.getStorageSync('memberId'),
      });
      if (this.data.identity == 1) { // 管理员
        var date = util.formatTime(new Date()).substring(0, 10);
        that.setData({
          isLogin: true,
          toDate: date,
          chooseDate: date,
          toMonth: date.substring(0, 7),
          chooseMonth: date.substring(0, 7),
          showToClean: true,
        });
        that.loadStroeList();
      } else {
        that.setData({
          isLogin: true,
        });
        that.loadStroeClean();
        // that.loadCleanRoom();
      }
    }
    
  },

  chooseRoom: function (e) {
    
    var $data = e.currentTarget.dataset;
    console.log($data.bean.storeName);
    var openStartTImeFull = util.formatTime(new Date());
    var openStartTime = openStartTImeFull.substring(0, 16);
    var openFinishTImeFull = util.endFormatTime(new Date(), 2);
    var openFinishTime = openFinishTImeFull.substring(0, 16);

    if ($data.bean.state == "1") {
      this.setData({
        showRoom: true,
        currentRoom: e.currentTarget.dataset,
        roomType: '0',
        changeId: -1,
        choseRoomData: $data.bean,
        openStartTime: openStartTime,
        openFinishTime: openFinishTime,
        openStartTImeFull: openStartTImeFull,
        openFinishTImeFull: openFinishTImeFull,
        openDurOur: 2,
        timeIndex: 1,
        chooseStatus: $data.bean.state,
        currentTime: openStartTime,
      });
    } else if($data.bean.state == "2"){
      this.setData({
        showRoom: true,
        roomType: '1',
        changeId: -1,
        choseRoomData: $data.bean,
        openStartTime: openStartTime,
        openFinishTime: openFinishTime,
        openStartTImeFull: openStartTImeFull,
        openFinishTImeFull: openFinishTImeFull,
        openDurOur: 2,
        timeIndex: 1,
        chooseStatus: $data.bean.state,
        currentTime: openStartTime,
      });
    } else if($data.bean.state == "0"){
      this.setData({
        showRoom: true,
        roomType: '2',
        changeId: -1,
        choseRoomData: $data.bean,
        openStartTime: openStartTime,
        openFinishTime: openFinishTime,
        openStartTImeFull: openStartTImeFull,
        openFinishTImeFull: openFinishTImeFull,
        openDurOur: 2,
        timeIndex: 1,
        chooseStatus: $data.bean.state,
        currentTime: openStartTime,
      });
    } else if($data.bean.state == "3"){
      this.setData({
        showRoom: true,
        roomType: '3',
        changeId: -1,
        choseRoomData: $data.bean,
        openStartTime: openStartTime,
        openFinishTime: openFinishTime,
        openStartTImeFull: openStartTImeFull,
        openFinishTImeFull: openFinishTImeFull,
        openDurOur: 2,
        timeIndex: 1,
        chooseStatus: $data.bean.state,
        currentTime: openStartTime,
      });
    }
    // 仅在使用中的房间才支持换包
    if($data.bean.state == 2){
      this.loadRoomCanCheck();
    }
  },

  loadRoomCanCheck() {
    http.request({
      showLoading: true,
      url: api.commutativeItemList,
      data: {
        id: this.data.choseRoomData.id,
        type: 1,
      },
    }).then(res => {
      if (res.data.code == 200 && res.data.result != null) {
        this.setData({
          'roomcancheckList': res.data.result,
        })
      } else {
        wx.showToast({
          title: '服务器异常，返回空列表',
          icon: "none",
          duration: 2000
        })
        this.setData({
          'roomcancheckList': '',
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  /**
   * 日报点击
   */
  tapDay(e) {
    this.setData({
      dataType: '0',
    })
    this.loadBusinessData();
  },
  /**
   * 月报点击
   */
  tapMonth(e) {
    this.setData({
      dataType: '1',
    })
    this.loadBusinessData();
  },
  /**
   * 日期选择
   */
  bindDateChange(e) {
    this.setData({
      chooseDate: e.detail.value,
    })
    this.loadBusinessData();
  },
  /**
   * 月份选择
   */
  bindMonthChange(e) {
      this.setData({
          chooseMonth: e.detail.value,
      })
      this.loadBusinessData();
  },  
  onPickerChange: function (e) {
    var openStartTime = e.detail.dateString;
    var openStartTImeFull = openStartTime + ":00";
    var openFinishTImeFull;
    if(this.data.timeIndex == 0){
      openFinishTImeFull = util.endFormatTime(new Date(openStartTImeFull.replace(/-/g, "/")), 1);
      this.setData({
        openDurOur: 1,
      })
    }else if(this.data.timeIndex == 1){
      openFinishTImeFull = util.endFormatTime(new Date(openStartTImeFull.replace(/-/g, "/")), 2);
      this.setData({
        openDurOur: 2,
      })
    }else if(this.data.timeIndex == 2){
      openFinishTImeFull = util.endFormatTime(new Date(openStartTImeFull.replace(/-/g, "/")), 3);
      this.setData({
        openDurOur: 3,
      })
    }else if(this.data.timeIndex == 3){
      openFinishTImeFull = util.endFormatTime(new Date(openStartTImeFull.replace(/-/g, "/")), 4);
      this.setData({
        openDurOur: 4,
      })
    }else if(this.data.timeIndex == 4){
      openFinishTImeFull = util.endFormatTime(new Date(openStartTImeFull.replace(/-/g, "/")), 5);
      this.setData({
        openDurOur: 5,
      })
    }
    console.log(openFinishTImeFull+"*------------");
    var openFinishTime = openFinishTImeFull.substring(0, 16);
    this.setData({
      openStartTime: openStartTime,
      openFinishTime: openFinishTime,
      openStartTImeFull: openStartTImeFull,
      openFinishTImeFull: openFinishTImeFull,
    })
   },
   
  timeChooseThree(e) {
    // var openStartTImeFull = util.formatTime(new Date());
    // var openStartTime = openStartTImeFull.substring(0, 16);
    var openFinishTImeFull = util.endFormatTime(new Date(this.data.openStartTImeFull.replace(/-/g, "/")), 1);
    // var openFinishTImeFull = util.endFormatTime(new Date(), 3);
    var openFinishTime = openFinishTImeFull.substring(0, 16);
    this.setData({
      timeIndex: 0,
      // openStartTime: openStartTime,
      openFinishTime: openFinishTime,
      // openStartTImeFull: openStartTImeFull,
      openFinishTImeFull: openFinishTImeFull,
      openDurOur: 1,
    })
  },
  timeChooseFour(e) {
    // var openStartTImeFull = util.formatTime(new Date());
    // var openStartTime = openStartTImeFull.substring(0, 16);
    var openFinishTImeFull = util.endFormatTime(new Date(this.data.openStartTImeFull.replace(/-/g, "/")), 2);
    var openFinishTime = openFinishTImeFull.substring(0, 16);
    this.setData({
      timeIndex: 1,
      // openStartTime: openStartTime,
      openFinishTime: openFinishTime,
      // openStartTImeFull: openStartTImeFull,
      openFinishTImeFull: openFinishTImeFull,
      openDurOur: 2,
    })
  },
  timeChooseFive(e) {
    // var openStartTImeFull = util.formatTime(new Date());
    // var openStartTime = openStartTImeFull.substring(0, 16);
    var openFinishTImeFull = util.endFormatTime(new Date(this.data.openStartTImeFull.replace(/-/g, "/")), 3);
    var openFinishTime = openFinishTImeFull.substring(0, 16);
    this.setData({
      timeIndex: 2,
      // openStartTime: openStartTime,
      openFinishTime: openFinishTime,
      // openStartTImeFull: openStartTImeFull,
      openFinishTImeFull: openFinishTImeFull,
      openDurOur: 3,
    })
  },
  timeChooseSix(e) {
    // var openStartTImeFull = util.formatTime(new Date());
    // var openStartTime = openStartTImeFull.substring(0, 16);
    var openFinishTImeFull = util.endFormatTime(new Date(this.data.openStartTImeFull.replace(/-/g, "/")), 4);
    var openFinishTime = openFinishTImeFull.substring(0, 16);
    this.setData({
      timeIndex: 3,
      // openStartTime: openStartTime,
      openFinishTime: openFinishTime,
      // openStartTImeFull: openStartTImeFull,
      openFinishTImeFull: openFinishTImeFull,
      openDurOur: 4,
    })
  },
  timeChooseSeven(e) {
    var openStartTImeFull = util.formatTime(new Date());
    var openStartTime = openStartTImeFull.substring(0, 16);
    var openFinishTImeFull = util.endFormatTime(new Date(this.data.openStartTImeFull.replace(/-/g, "/")), 5);
    var openFinishTime = openFinishTImeFull.substring(0, 16);
    this.setData({
      timeIndex: 4,
      // openStartTime: openStartTime,
      openFinishTime: openFinishTime,
      // openStartTImeFull: openStartTImeFull,
      openFinishTImeFull: openFinishTImeFull,
      openDurOur: 5,
    })
  },

  roomManage(e) {
    let windowRoomType = this.data.choseRoomData.state;
    if (windowRoomType == "0" ) {
      wx.showToast({
        title: "该包间当前状态，无法进行开启操作",
        icon: "none",
        duration: 2000
      });
    } else {
      this.setData({
        roomType: '0',
      })
    }
  },

  roomChange(e) {
    let windowRoomType = this.data.choseRoomData.state;
    if (windowRoomType != "2") {
      wx.showToast({
        title: "仅使用中的房间可以进行换包操作",
        icon: "none",
        duration: 2000
      });
    } else {
      this.loadRoomCanCheck();
      this.setData({
        'choseRoomSelect': '',
        roomType: '1',
      })
    }

  },
  /**
   * 房间弹窗-状态
   */
  roomStatus(e) {
    this.setData({
      roomType: '2',
    })
  },
  /**
   * 房间弹窗-开关门
   */
  roomDoor(e) {
    this.setData({
      roomType: '3',
    })
  },
  openDoor(e) {
    this.setData({
      doorStatus: '1',
    })
  },
  closeDoor(e) {
    this.setData({
      doorStatus: '0',
    })
  },

  /**
   * 状态选中切换
   */
  statusChooseFree(e) {
    this.setData({
      chooseStatus: '0',
    })
  },
  statusChooseUse(e) {
    this.setData({
      chooseStatus: '1',
    })
  },
  statusChooseClearn(e) {
    this.setData({
      chooseStatus: '2',
    })
  },
  statusChooseFix(e) {
    this.setData({
      chooseStatus: '3',
    })
  },

  confirmDoor(e) {
    http.request({
      showLoading: true,
      shake: true,
      url: api.openRoom,
      data: {
        itemId: this.data.choseRoomData.id,
        operationType: this.data.doorStatus,
      },
    }).then(res => {
      if (res.data.code == 200 && res.data.result) {
        if (this.data.doorStatus == 1) {
          this.hiddenRoom();
          setTimeout(function () {
            wx.showToast({
              title: "操作成功,请直接手动开门",
              icon: "none",
              duration: 2000
            });
          }, 1000);
        } else {
          setTimeout(function () {
            wx.showToast({
              title: "操作成功,请记得关好房门",
              icon: "none",
              duration: 2000
            });
          }, 1000);
        }
        this.loadStroeDetail();
      }else if(res.data.code == 200 && !res.data.reulst){
        setTimeout(function () {
          wx.showToast({
            title: "智能设备当前处于离线状态，请稍后重试",
            icon: "none",
            duration: 2000
          });
        }, 1000);
      } else {
        wx.showToast({
          title: '操作失败,请检设备网络环境是否正常',
          icon: "none",
          duration: 2000
        });
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
    });
  },

  /**
   * 更换房间
   */
  changeRoom() {
    http.request({
      showLoading: true,
      shake: true,
      url: api.changeTradeItem,
      data: {
        itemId: this.data.choseRoomSelect.itemId,
        originalId: this.data.choseRoomData.id,
        type: 1,
      },
    }).then(res => {
      if (res.data.code == 200) {
        if (res.data.success) {
          this.hiddenRoom();
          setTimeout(function () {
            wx.showToast({
              title: '换包成功',
              icon: "none",
              duration: 2000
            });
          }, 1000);
          this.setData({
              'choseRoomSelect': '',
          }),
          this.loadStroeDetail();
        } else {
          setTimeout(function () {
            wx.showToast({
              title: '换包失败,请稍后再试',
              icon: "none",
              duration: 2000
            });
          }, 1000);
        }
      }
    }).catch(err => {
      setTimeout(function () {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      }, 1000);
    });
  },

  /**
   * 修改房间状态
   */
  changeRoomType() {
    let choseRoomData = this.data.choseRoomData;
    http.request({
      showLoading: true,
      shake: true,
      url: api.modifyItemInfo,
      method: 'POST',
      data: {
        aocn: choseRoomData.aocn,
        aocnPathAddress: choseRoomData.aocnPathAddress,
        describes: choseRoomData.describes,
        enabled: choseRoomData.enabled,
        itemLogo: choseRoomData.itemLogo,
        itemName: choseRoomData.itemName,
        pictures: choseRoomData.pictures,
        price: choseRoomData.price,
        id: choseRoomData.id,
        smartAudio: choseRoomData.smartAudio,
        smartLock: choseRoomData.smartLock,
        state: this.data.chooseStatus,
        storeId: choseRoomData.storeId,
        unit: choseRoomData.unit,
        operateType : 1,
      },
    }).then(res => {
      if (res.data.code == 200) {
        this.hiddenRoom();
        setTimeout(function () {
          wx.showToast({
            title: '修改状态成功',
            icon: "none",
            duration: 2000
          });
        }, 1000);
        this.loadStroeDetail();
      } else {
        if (res.data.message == null || res.data.message == "") {
          setTimeout(function () {
            wx.showToast({
              title: '修改状态失败,请稍后再试',
              icon: "none",
              duration: 2000
            });
          }, 1000);
        } else {
          setTimeout(function () {
            wx.showToast({
              title: res.data.message,
              icon: "none",
              duration: 2000
            });
          }, 1000);
        }
      }
    }).catch(err => {
      setTimeout(function () {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      }, 1000);
    });
  },

  changeRoomChoose: function (e) {
    var $data = e.currentTarget.dataset;
    if ($data.bean.itemName == this.data.choseRoomData.itemName) {
      wx.showToast({
        title: "当前正在使用此包间，请选择其他包间更换",
        icon: "none",
        duration: 2000
      });
    } else {
      this.setData({
        choseRoomSelect: $data.bean,
      });
    }
  },
  preventTouchMove:function(e) {

  },
  toRecharge(e){
    var merchantId = this.data.appdata.memberId;
    wx.navigateTo({
      url: '/pages/recharge/recharge?merchantId=' + merchantId,
    })
  },
  toCoupon(e){
    var storeId = this.data.storeData.id;
    var merchantId = this.data.appdata.memberId;
    wx.navigateTo({
      url: '/pages/sendCoupon/sendCoupon?storeId=' + storeId  + '&merchantId=' + merchantId,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("onshow =================");
    if(this.data.identity == 1 && this.data.roomList.length > 0){
      console.log("onshow 店主===============");
      this.loadStroeDetail();
      this.loadBusinessData();
      // this.loadincome();
    }
    if(this.data.identity == 0 && this.data.storeList.length > 0){
      console.log("onshow 清洁工====================");
      this.loadCleanRoom();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if(this.data.isLogin && this.data.identity == 0){
      this.loadCleanRoom();
      setTimeout(function () {
        wx.stopPullDownRefresh();
      }, 500);
    }else if(this.data.isLogin && this.data.identity == 1){
      this.loadStroeDetail();
      this.loadBusinessData();
      // this.loadincome();
      setTimeout(function () {
        wx.stopPullDownRefresh();
      }, 500);
    }else{
      setTimeout(function () {
        wx.stopPullDownRefresh();
      }, 100);
    }
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})